package com.report;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import javax.servlet.http.HttpServletResponse;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.renderer.category.CategoryItemRenderer;
import org.jfree.data.category.DefaultCategoryDataset;
import com.bean.MasterBean;
import com.dao.ReportDao;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Font.FontFamily;
import com.itextpdf.text.pdf.DefaultFontMapper;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfTemplate;
import com.itextpdf.text.pdf.PdfWriter;
import com.util.AppConstant;
import com.util.ChartConstant;

@ManagedBean
@ViewScoped
public class PerfReportBean implements Serializable {

	private static final long serialVersionUID = 1L;
	@ManagedProperty(value="#{master}")
	private MasterBean masterBean ;
	
	private int showSupl = 0;
	private int showGraph = 0;
	private PerfReportTo reportTo;
	private List<SelectItem> suplList;
	private int graphWidth = 500;
	
	private  Map<String, ArrayList<BigDecimal>> scoreMap = new LinkedHashMap<String,ArrayList<BigDecimal>>();
	private  Map<String, ArrayList<String>> scoreMap1 = new LinkedHashMap<String,ArrayList<String>>();
    private ArrayList<String> names = new ArrayList<String>();
    private ArrayList<String> colors = new ArrayList<String>();
    ArrayList<ScoreTo> dataList = null;
	ReportDao reportDao = null;
	
	
	
	public PerfReportBean(){
		reportDao = new ReportDao();
		
		System.out.println("---Report bean Initialized ---");
		
	}
	
	public void genSupplierList(){
		for(SelectItem sel : masterBean.getMatList()){
			if(((Integer)sel.getValue()).intValue() == this.reportTo.getMatGrpId()){
				this.reportTo.setMatGrpName(sel.getLabel());
			}
		}
		for(SelectItem sel : masterBean.getQuaterList()){
			if(((Integer)sel.getValue()).intValue() == this.reportTo.getAssPeriod()){
				this.reportTo.setAssPerName(sel.getLabel()+"-"+this.reportTo.getAssYear());
			}
		}
		
		setSuplList(reportDao.getSuplListAsMaterialGpr(this.reportTo));
		System.out.println("---Report bean Get customized Supplier list ---");
	}
	
	public void generateReport(){
		/*String s[] = {"6","7"};
		reportTo.setAssPeriod(1);
		reportTo.setAssYear(2012);
		reportTo.setSelSuplList(s);
		reportTo.setMatGrpId(2);
		scoreMap = reportDao.getAddedValueScore(reportTo);*/
		if(AppConstant.ASS_TYPE_SITE == reportTo.getAssTypeId()){
			scoreMap = reportDao.getSuplScoreReport(reportTo);
			
			names.add("Operational Performance");
	        names.add("Site Support Score");
	        names.add("Supplier Capability Score");
	        
	        colors.add("#5db2c2");
	        colors.add("#b0343c");
	        colors.add("#dd9f2c");
	        
	        getDataTabHeader();
		}
		if(AppConstant.ASS_TYPE_SUPL_CAP == reportTo.getAssTypeId()){
			scoreMap1 = reportDao.getAddedValueScore(reportTo);
			setNames(reportDao.getCategoryList(AppConstant.ASS_TYPE_SUPL_CAP));
			colors.add("#5db2c2");
	        colors.add("#b0343c");
	        colors.add("#dd9f2c");
	        colors.add("#778ab0");
	        colors.add("#B87333");
	        colors.add("#2E548A");
	        
	        colors.add("#696d67");
	        colors.add("#24B300");
	        colors.add("#24B300");
	        getAddValDataTab();
		}
		
		if(reportTo.getSelSuplList().length > 1){
			setGraphWidth(400 + 150 * reportTo.getSelSuplList().length);
		}
		
        System.out.println("--Key Value ---" );
	}
	
	public void getAddValDataTab(){
		ScoreTo scrTo = null;
		dataList = new ArrayList<ScoreTo>();
		if(names != null){
			scrTo = new ScoreTo();
			scrTo.setSuplName(" ");
			scrTo.setParam1(names.get(0));
			scrTo.setParam2(names.get(1));
			scrTo.setParam3(names.get(2));
			scrTo.setParam4(names.get(3));
			scrTo.setParam5(names.get(4));
			scrTo.setParam6(names.get(5));
			scrTo.setParam7(names.get(6));
			scrTo.setParam8(names.get(7));
			dataList.add(scrTo);
		}
		
		Collection<String> colKey = this.scoreMap1.keySet();
		for(String strKey : colKey){
			scrTo = new ScoreTo();
			scrTo.setSuplName(strKey);
			ArrayList<String> scrValue = this.scoreMap1.get(strKey);
			if(scrValue != null){
				scrTo.setParam1(scrValue.get(0));
				scrTo.setParam2(scrValue.get(1));
				scrTo.setParam3(scrValue.get(2));
				scrTo.setParam4(scrValue.get(3));
				scrTo.setParam5(scrValue.get(4));
				scrTo.setParam6(scrValue.get(5));
				scrTo.setParam7(scrValue.get(6));
				scrTo.setParam8(scrValue.get(7));
			}
			dataList.add(scrTo);
			System.out.println("--* ---" );
		}
	}
	
	public void getDataTabHeader(){
		ScoreTo scrTo = null;
		dataList = new ArrayList<ScoreTo>();
		Collection<String> colKey = this.scoreMap.keySet();
		for(String strKey : colKey){
			
			scrTo = new ScoreTo();
			scrTo.setSuplName(strKey);
			ArrayList<BigDecimal> scrValue = this.scoreMap.get(strKey);
			if(scrValue != null){
				if(scrValue.get(0) != null){
					scrTo.setOpScore(scrValue.get(0));
				}
				if(scrValue.get(1) != null){
					scrTo.setSiteScore(scrValue.get(1));
				}
				if(scrValue.size() >= 3 && scrValue.get(2) != null  ){
					scrTo.setAddValScore(scrValue.get(2));
				}
			}
			this.dataList.add(scrTo);
		}
	}
	
	
	public void exportPDF_addVal(){
		PdfWriter writer = null;
	    try {
	    	    	
	        HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
	        PdfPTable table = null;
	        
			Document document = new Document(PageSize.A4.rotate());
			String fileName = this.reportTo.getMatGrpName()+"_"+this.reportTo.getAssPerName();
			response.setHeader( "Content-Disposition", "attachment; filename="+fileName+".pdf" ); 
	        response.setContentType("application/pdf");  
			
	        // document=new Document();
	        writer = PdfWriter.getInstance(document,response.getOutputStream());
	       		        
	 	    document.open();  
	 	    Paragraph par = new Paragraph("Benchmark Supplier Added Value Report",new Font(FontFamily.HELVETICA, 13, Font.BOLD));
	 	    par.setAlignment(Element.ALIGN_CENTER);
		 	    
	 	    document.add(par);
            document.add(new Paragraph(" "));
            table = new PdfPTable(4);
            table.setWidthPercentage(95);
            table.setHorizontalAlignment(Element.ALIGN_CENTER);
            PdfPCell cell = new PdfPCell();
            cell.setGrayFill(0.9f);
			cell.setPhrase(new Phrase("Material Group Name :".toUpperCase(), ChartConstant.fontBold1));
			//cell.setHorizontalAlignment(2);
			table.addCell(cell);
			cell = new PdfPCell();
			cell.setPhrase(new Phrase(this.reportTo.getMatGrpName(), ChartConstant.font1));
			table.addCell(cell);
			
			cell = new PdfPCell();
			cell.setGrayFill(0.9f);
			cell.setPhrase(new Phrase("Assessment Period :".toUpperCase(), ChartConstant.fontBold1));
			table.addCell(cell);
			
			cell = new PdfPCell();
			cell.setHorizontalAlignment(Element.ALIGN_CENTER);
			cell.setPhrase(new Phrase(this.reportTo.getAssPerName(), ChartConstant.font1));
			table.addCell(cell);
			
			table.completeRow();
			document.add(table);
	            
			// adding the Graph
			
	        PdfContentByte contentByte = writer.getDirectContent();
	        PdfTemplate template = contentByte.createTemplate(ChartConstant.CHART_WIDTH, ChartConstant.CHART_HEIGHT);
	        Graphics2D graphics2d = template.createGraphics(ChartConstant.CHART_WIDTH, ChartConstant.CHART_HEIGHT,
	                new DefaultFontMapper());
	        Rectangle2D rectangle2d = new Rectangle2D.Double(0, 0, ChartConstant.CHART_WIDTH, ChartConstant.CHART_HEIGHT);
	 
	        generateChartData_addval().draw(graphics2d, rectangle2d);
	 
	        graphics2d.dispose();
	        contentByte.addTemplate(template, ChartConstant.POSITION_X, ChartConstant.POSITION_Y);
	        
	        for(int i = 0 ; i < 18 ; i++){
	        	document.add(new Paragraph(" "));
	        }
		        
	        //data table
	        table = new PdfPTable(9);
	     
	        table.setWidthPercentage(100);
            table.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell = new PdfPCell();
            cell.setBorder(0);
            //cell.setGrayFill(0.9f);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
			cell.setPhrase(new Phrase(" ".toUpperCase(), ChartConstant.fontBold1));
			table.addCell(cell);
			cell = new PdfPCell();
			cell.setHorizontalAlignment(Element.ALIGN_CENTER);
			cell.setGrayFill(0.8f);
			for(String str : names){
				cell.setPhrase(new Phrase(str.toUpperCase(), ChartConstant.fontBold1));
				table.addCell(cell);
			}
			table.completeRow();
		        
	       for(ScoreTo scrTo : dataList.subList(1, dataList.size())){
	        	cell = new PdfPCell();
	        	cell.setGrayFill(0.9f);
				cell.setHorizontalAlignment(Element.ALIGN_CENTER);
				cell.setPhrase(new Phrase(scrTo.getSuplName()));
				table.addCell(cell);
				cell = new PdfPCell();
				cell.setHorizontalAlignment(Element.ALIGN_CENTER);
				cell.setPhrase(new Phrase(scrTo.getParam1()));
				table.addCell(cell);
				cell.setPhrase(new Phrase(scrTo.getParam2().toString()));
				table.addCell(cell);
				cell.setPhrase(new Phrase(scrTo.getParam3().toString()));
				table.addCell(cell);
				cell.setPhrase(new Phrase(scrTo.getParam4()));
				table.addCell(cell);
				cell.setPhrase(new Phrase(scrTo.getParam5().toString()));
				table.addCell(cell);
				cell.setPhrase(new Phrase(scrTo.getParam6().toString()));
				table.addCell(cell);
				cell.setPhrase(new Phrase(scrTo.getParam7().toString()));
				table.addCell(cell);
				cell.setPhrase(new Phrase(scrTo.getParam8().toString()));
				table.addCell(cell);
				table.completeRow();
	        }
	        document.add(table);
	        document.close(); 
	        
			if (!FacesContext.getCurrentInstance().getResponseComplete()) 
				FacesContext.getCurrentInstance().responseComplete(); 
	    }
	    catch (Exception e) { 
	        e.printStackTrace();
	    } 
	}
	
	public void exportPDF(){
		PdfWriter writer = null;
	    try {
	    	    	
	        HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
	        PdfPTable table = null;
	        
			Document document = new Document(PageSize.A4.rotate());
			String fileName = this.reportTo.getMatGrpName()+"_"+this.reportTo.getAssPerName();
			response.setHeader( "Content-Disposition", "attachment; filename="+fileName+".pdf" ); 
	        response.setContentType("application/pdf");  
			
	        // document=new Document();
	        writer = PdfWriter.getInstance(document,response.getOutputStream());
	       		        
	 	    document.open();  
	 	    Paragraph par = new Paragraph("Benchmark Supplier/s Performance Report",new Font(FontFamily.HELVETICA, 13, Font.BOLD));
	 	    par.setAlignment(Element.ALIGN_CENTER);
		 	    
	 	    document.add(par);
            document.add(new Paragraph(" "));
            table = new PdfPTable(4);
            table.setWidthPercentage(95);
            table.setHorizontalAlignment(Element.ALIGN_CENTER);
            PdfPCell cell = new PdfPCell();
            cell.setGrayFill(0.9f);
			cell.setPhrase(new Phrase("Material Group Name :".toUpperCase(), ChartConstant.fontBold));
			//cell.setHorizontalAlignment(2);
			table.addCell(cell);
			cell = new PdfPCell();
			cell.setPhrase(new Phrase(this.reportTo.getMatGrpName(), ChartConstant.font));
			table.addCell(cell);
			
			cell = new PdfPCell();
			cell.setGrayFill(0.9f);
			cell.setPhrase(new Phrase("Assessment Period :".toUpperCase(), ChartConstant.fontBold));
			table.addCell(cell);
			
			cell = new PdfPCell();
			cell.setHorizontalAlignment(Element.ALIGN_CENTER);
			cell.setPhrase(new Phrase(this.reportTo.getAssPerName(), ChartConstant.font));
			table.addCell(cell);
			
			table.completeRow();
			document.add(table);
	            
			// adding the Graph
			
	        PdfContentByte contentByte = writer.getDirectContent();
	        PdfTemplate template = contentByte.createTemplate(ChartConstant.CHART_WIDTH, ChartConstant.CHART_HEIGHT);
	        Graphics2D graphics2d = template.createGraphics(ChartConstant.CHART_WIDTH, ChartConstant.CHART_HEIGHT,
	                new DefaultFontMapper());
	        Rectangle2D rectangle2d = new Rectangle2D.Double(0, 0, ChartConstant.CHART_WIDTH, ChartConstant.CHART_HEIGHT);
	 
	        generateChartData().draw(graphics2d, rectangle2d);
	 
	        graphics2d.dispose();
	        contentByte.addTemplate(template, ChartConstant.POSITION_X, ChartConstant.POSITION_Y);
	        
	        for(int i = 0 ; i < 20 ; i++){
	        	document.add(new Paragraph(" "));
	        }
		        
	        //data table
	        table = new PdfPTable(4);
	     
	        table.setWidthPercentage(100);
            table.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell = new PdfPCell();
            cell.setBorder(0);
            //cell.setGrayFill(0.9f);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
			cell.setPhrase(new Phrase(" ".toUpperCase(), ChartConstant.fontBold));
			table.addCell(cell);
			cell = new PdfPCell();
			cell.setHorizontalAlignment(Element.ALIGN_CENTER);
			cell.setGrayFill(0.8f);
			cell.setPhrase(new Phrase("Group Op Score ".toUpperCase(), ChartConstant.fontBold));
			table.addCell(cell);
			cell.setPhrase(new Phrase("Site Support Score ".toUpperCase(), ChartConstant.fontBold));
			table.addCell(cell);
			cell.setPhrase(new Phrase("Value Added Score ".toUpperCase(), ChartConstant.fontBold));
			table.addCell(cell);
	        table.completeRow();
		        
	        for(ScoreTo scrTo : dataList){
	        	cell = new PdfPCell();
	        	cell.setGrayFill(0.9f);
				cell.setHorizontalAlignment(Element.ALIGN_CENTER);
				cell.setPhrase(new Phrase(scrTo.getSuplName()));
				table.addCell(cell);
				cell = new PdfPCell();
				cell.setHorizontalAlignment(Element.ALIGN_CENTER);
				cell.setPhrase(new Phrase(scrTo.getOpScore().toString()));
				table.addCell(cell);
				cell.setPhrase(new Phrase(scrTo.getSiteScore().toString()));
				table.addCell(cell);
				cell.setPhrase(new Phrase(scrTo.getAddValScore().toString()));
				table.addCell(cell);
				table.completeRow();
	        }
	        document.add(table);
	        document.close(); 
	        
			if (!FacesContext.getCurrentInstance().getResponseComplete()) 
				FacesContext.getCurrentInstance().responseComplete(); 
	    }
	    catch (Exception e) { 
	        e.printStackTrace();
	    } 
	}
	
	
	
	public JFreeChart generateChartData_addval(){
		DefaultCategoryDataset dataSet = new DefaultCategoryDataset();
		Collection<String> colKey = this.scoreMap1.keySet();
		
		//int i = 0;
		
		for(String strKey : colKey){
			ArrayList<String> scrValue = this.scoreMap1.get(strKey);
			for(int i = 0; i <names.size() ; i++){
				dataSet.addValue(new Double(scrValue.get(i)).doubleValue(), names.get(i), strKey);
			}
			//dataSet.addValue(scrValue.get(0).doubleValue(), "Group Op Score", strKey);
		//	dataSet.addValue(scrValue.get(1).doubleValue(), "Site Support Score", strKey);
		//	dataSet.addValue(scrValue.get(2).doubleValue(), "Value Added Score", strKey);
		}
		
		JFreeChart chart = ChartFactory.createBarChart(
                "Score Chart", "<------- Suppliers ------->", "<---- Score ---->",
                dataSet, PlotOrientation.VERTICAL, true, true, false);
        CategoryPlot plot = chart.getCategoryPlot();
        plot.setBackgroundPaint(new Color(0xE4E4E4));
       
       // chart.setBackgroundPaint(new Color(0xE4E4E4));
        
      final BarRenderer renderer = (BarRenderer) plot.getRenderer();
        renderer.setDrawBarOutline(false);
        renderer.setMaximumBarWidth(0.10);
      
        CategoryItemRenderer rend = plot.getRenderer();
        rend.setBaseItemLabelsVisible( Boolean.TRUE);
       for(int i=0; i< dataSet.getRowCount() ; i++){
    	   renderer.setSeriesPaint(i, ChartConstant.getPaint().get(i));
    	   rend.setSeriesItemLabelsVisible(i, true);
        	//i++;
        }
       
     // set up gradient paints for series...
       
    /*   GradientPaint gp0 = new GradientPaint(
        0.0f, 0.0f, new Color(0x5DB2C2),
        0.0f, 0.0f, Color.lightGray
        );
        GradientPaint gp1 = new GradientPaint(
        0.0f, 0.0f, new Color(0xB0343C),
        1, 1, Color.white,true
        );
        GradientPaint gp2 = new GradientPaint(
        0.0f, 0.0f, new Color(0xDD9F2C),
        0.0f, 0.0f, Color.lightGray
        );
        renderer.setSeriesPaint(0, gp0);
        renderer.setSeriesPaint(1, gp1);
        renderer.setSeriesPaint(2, gp2);
        CategoryItemRenderer rend = plot.getRenderer();
        rend.setBaseItemLabelsVisible( Boolean.TRUE);
       /* rend.setSeriesItemLabelsVisible(0, true);
        rend.setSeriesItemLabelsVisible(1, true);
        rend.setSeriesItemLabelsVisible(2, true);*/
        return chart;
	}
	public JFreeChart generateChartData(){
		DefaultCategoryDataset dataSet = new DefaultCategoryDataset();
		Collection<String> colKey = this.scoreMap.keySet();
		
		//int i = 0;
		
		for(String strKey : colKey){
			ArrayList<BigDecimal> scrValue = this.scoreMap.get(strKey);
			dataSet.addValue(scrValue.get(0).doubleValue(), "Group Op Score", strKey);
			dataSet.addValue(scrValue.get(1).doubleValue(), "Site Support Score", strKey);
			dataSet.addValue(scrValue.get(2).doubleValue(), "Value Added Score", strKey);
		}
		
		JFreeChart chart = ChartFactory.createBarChart(
                "Score Chart", "Suppliers", "Score",
                dataSet, PlotOrientation.VERTICAL, true, true, false);
        CategoryPlot plot = chart.getCategoryPlot();
        plot.setBackgroundPaint(new Color(0xE4E4E4));
       
       // chart.setBackgroundPaint(new Color(0xE4E4E4));
        
      final BarRenderer renderer = (BarRenderer) plot.getRenderer();
        renderer.setDrawBarOutline(false);
        renderer.setMaximumBarWidth(0.10);
      
        CategoryItemRenderer rend = plot.getRenderer();
        rend.setBaseItemLabelsVisible( Boolean.TRUE);
       for(int i=0; i< dataSet.getRowCount() ; i++){
    	   renderer.setSeriesPaint(i, ChartConstant.getPaint().get(i));
    	   rend.setSeriesItemLabelsVisible(i, true);
        	//i++;
        }
       
     // set up gradient paints for series...
       
    /*   GradientPaint gp0 = new GradientPaint(
        0.0f, 0.0f, new Color(0x5DB2C2),
        0.0f, 0.0f, Color.lightGray
        );
        GradientPaint gp1 = new GradientPaint(
        0.0f, 0.0f, new Color(0xB0343C),
        1, 1, Color.white,true
        );
        GradientPaint gp2 = new GradientPaint(
        0.0f, 0.0f, new Color(0xDD9F2C),
        0.0f, 0.0f, Color.lightGray
        );
        renderer.setSeriesPaint(0, gp0);
        renderer.setSeriesPaint(1, gp1);
        renderer.setSeriesPaint(2, gp2);
        CategoryItemRenderer rend = plot.getRenderer();
        rend.setBaseItemLabelsVisible( Boolean.TRUE);
       /* rend.setSeriesItemLabelsVisible(0, true);
        rend.setSeriesItemLabelsVisible(1, true);
        rend.setSeriesItemLabelsVisible(2, true);*/
        return chart;
	}
	
	
	
	public int getShowSupl() {
		return showSupl;
	}
	public void setShowSupl(int showSupl) {
		this.showSupl = showSupl;
	}
	public int getShowGraph() {
		return showGraph;
	}
	public void setShowGraph(int showGraph) {
		this.showGraph = showGraph;
	}
	public PerfReportTo getReportTo() {
		if(reportTo == null){
			reportTo = new PerfReportTo();
		}
		return reportTo;
	}
	public void setReportTo(PerfReportTo reportTo) {
		this.reportTo = reportTo;
	}

	public void setSuplList(List<SelectItem> suplList) {
		this.suplList = suplList;
	}

	public List<SelectItem> getSuplList() {
		return suplList;
	}
	
	public ArrayList<String> getNames(){
        return names;
    } 

    public ArrayList<String> getColors(){
        return colors;
    }

	public Map<String, ArrayList<BigDecimal>> getScoreMap() {
		return scoreMap;
	}
	public Map<String, ArrayList<String>> getScoreMap1() {
		return scoreMap1;
	}

	public ArrayList<ScoreTo> getDataList() {
		return dataList;
	}

	public void setDataList(ArrayList<ScoreTo> dataList) {
		this.dataList = dataList;
	}

	public void setMasterBean(MasterBean masterBean) {
		this.masterBean = masterBean;
	}

	public void setNames(ArrayList<String> names) {
		this.names = names;
	}

	public void setGraphWidth(int graphWidth) {
		this.graphWidth = graphWidth;
	}

	public int getGraphWidth() {
		return graphWidth;
	}

}
